//
//  WBOAuthViewController.swift
//  weibo
//
//  Created by 林帆 on 2017/5/23.
//  Copyright © 2017年 林帆. All rights reserved.
//

import UIKit
import SVProgressHUD

// 通过 webview 加载新浪微博授权页面控制器
class WBOAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    override func loadView() {
        view = webView
        view.backgroundColor = UIColor.white
        webView.delegate = self as UIWebViewDelegate
        
        
        // 设置导航栏
        title = "登录新浪微博"
        
        //导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", width: 40, target: self, action: #selector(close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", width: 80, target: self, action: #selector(autoFill))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURL)"
        
        // 1 > URL  确定要访问的资源
        guard let url = URL(string: urlString)
            else {
                return
        }
         // 2 > 建立请求
        let request = URLRequest(url: url)
        
        // 3 > 加载请求
        webView.loadRequest(request)
        
    }

    @objc fileprivate func close() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    @objc fileprivate func autoFill() {
        // 准备 js
        let js = ""
        // 让 webview 执行 js
        webView.stringByEvaluatingJavaScript(from: js)
    }
}

extension WBOAuthViewController: UIWebViewDelegate {
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print("加载请求")
        return true
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}
